#coding:utf-8
from jenkins import Jenkins
import time

class jenkins_svn(object):
    def __init__(self):
        self.jenkins_url = ""
        self.username = ""
        self.password = ""

    def start_jk(self):
        jenkins_server = Jenkins(self.jenkins_url, username=self.username, password=self.password)
        return jenkins_server

    def build_info(self, project, server):
        # 获取jenkins 修改日志
        msg_data = ""
        build_data = server.get_job_info(project)  # 项目信息
        project_json = {}
        project_json["end_build_id"] = int(build_data['lastBuild']["number"])  # 最后一次构建的版本
        svn_data = server.get_build_info(project, project_json["end_build_id"])  # 最后一次构建的信息
        print(svn_data)
        project_json["svn_version"] = svn_data["changeSet"]["revisions"][0]["revision"]  # 项目版本号
        project_json["result"] = svn_data["result"]
        list_data = svn_data["changeSet"]["items"]
        for i in list_data:
            msg_data += i["msg"] + "\n"
        project_json["msg_data"] = msg_data
        return project_json


    def job_build(self, project, server):
        server.build_job(project) #开始build项目
        time.sleep(10)
        build_data = server.get_job_info(project)
        end_build_id = build_data['lastBuild']["number"] #获取当前构建的id

        status = True
        while status:
            build_status = server.get_build_info(project, end_build_id) #根据ID查看构建状态
            if not build_status["building"]:
                status = False
            else:
                print("正在构建")
                time.sleep(10)
        build_msg = self.build_info(project, server)
        if build_msg["result"] == "SUCCESS":
            build_msg["status"] = True
        else:
            build_msg["status"] = False
        return build_msg

if __name__ == "__main__":
    a = jenkins_svn()
    server = a.start_jk()
    b = a.job_build("T1WEB2", server)
    print(b)

